<template>
  <div class="analysis-container">
    <div v-loading="loading" class="performance-card">
      <div class="metrics-row">
        <div class="metric-item">
          <div class="metric-label">总收益率</div>
          <div class="metric-value positive">+18.73%</div>
          <div class="metric-trend">年化率 +6.42%</div>
        </div>
        <div class="metric-item">
          <div class="metric-label">夏普比率</div>
          <div class="metric-value">2.15</div>
          <div class="metric-trend">优秀</div>
        </div>
        <div class="metric-item">
          <div class="metric-label">最大回撤</div>
          <div class="metric-value negative">-8.7%</div>
          <div class="metric-trend">回撤期 2025-04-15</div>
        </div>
        <div class="metric-item">
          <div class="metric-label">胜率</div>
          <div class="metric-value">68.5%</div>
          <div class="metric-trend">总交易 367 次</div>
        </div>
      </div>

      <!-- 收益曲线图 -->
      <div class="chart-container">
        <div class="chart-header">
          <div class="select-group">
            <el-select v-model="timeRange" size="small" placeholder="所有周期">
              <el-option label="所有周期" value="all" />
              <el-option label="近一周" value="1w" />
              <el-option label="近一月" value="1m" />
              <el-option label="近三月" value="3m" />
            </el-select>
            <el-select v-model="compareWith" size="small" placeholder="沪深300">
              <el-option label="沪深300" value="hs300" />
              <el-option label="上证指数" value="sh" />
              <el-option label="BTC" value="btc" />
            </el-select>
          </div>
          <el-button size="small" plain>导出报告</el-button>
        </div>
        <div ref="profitChart" class="profit-chart"></div>
      </div>

      <!-- 收益分析 -->
      <div class="analysis-section">
        <div class="section-title">收益分析</div>
        <div class="analysis-grid">
          <div class="grid-item">
            <span class="item-label">年化收益率</span>
            <span class="item-value positive">24.8%</span>
          </div>
          <div class="grid-item">
            <span class="item-label">波动率</span>
            <span class="item-value">11.5%</span>
          </div>
          <div class="grid-item">
            <span class="item-label">夏普比率</span>
            <span class="item-value">2.03</span>
          </div>
          <div class="grid-item">
            <span class="item-label">信息比率</span>
            <span class="item-value">1.78</span>
          </div>
          <div class="grid-item">
            <span class="item-label">卡玛比率</span>
            <span class="item-value">0.78</span>
          </div>
        </div>
      </div>

      <!-- 风险分析 -->
      <div class="analysis-section">
        <div class="section-title">风险分析</div>
        <div class="analysis-grid">
          <div class="grid-item">
            <span class="item-label">最大持仓时间</span>
            <span class="item-value">5天</span>
          </div>
          <div class="grid-item">
            <span class="item-label">最大杠杆倍数</span>
            <span class="item-value">12X</span>
          </div>
          <div class="grid-item">
            <span class="item-label">下行波动</span>
            <span class="item-value">4.2%</span>
          </div>
          <div class="grid-item">
            <span class="item-label">恢复期</span>
            <span class="item-value">18天</span>
          </div>
          <div class="grid-item">
            <span class="item-label">Beta系数</span>
            <span class="item-value">0.65</span>
          </div>
        </div>
      </div>

      <!-- 交易分析 -->
      <div class="analysis-section">
        <div class="section-title">交易分析</div>
        <div class="trade-analysis-grid">
          <div class="grid-item">
            <span class="item-label">平均持仓时间</span>
            <span class="item-value">3.2天</span>
          </div>
          <div class="grid-item">
            <span class="item-label">平均盈利/交易</span>
            <span class="item-value positive">+0.52%</span>
          </div>
          <div class="grid-item">
            <span class="item-label">平均亏损/交易</span>
            <span class="item-value negative">-0.82%</span>
          </div>
          <div class="grid-item">
            <span class="item-label">盈亏比</span>
            <span class="item-value">1.78</span>
          </div>
          <div class="grid-item">
            <span class="item-label">总手续费</span>
            <span class="item-value">$1,245.67</span>
          </div>
        </div>
      </div>

      <!-- 图表分析 -->
      <div class="charts-section">
        <div class="chart-row">
          <div class="chart-col">
            <div class="chart-title">持仓产品分布</div>
            <div ref="positionPieChart" class="position-pie-chart"></div>
          </div>
          <div class="chart-col">
            <div class="chart-title">按时段分布</div>
            <div ref="timeBarChart" class="time-bar-chart"></div>
          </div>
        </div>
        <div class="chart-row">
          <div class="chart-col full-width">
            <div class="chart-title">持仓分布</div>
            <div ref="positionLineChart" class="position-line-chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from 'lodash-es'

export default {
  name: 'StrategyAnalysis',
  data() {
    return {
      timeRange: 'all',
      compareWith: 'hs300',
      charts: {
        profit: null,
        position: null,
        time: null,
        pie: null
      },
      loading: true,
      resizeObserver: null,
      // 模拟数据
      mockData: {
        profitData: [
          { date: '2024-01-01', value: 100 },
          { date: '2024-01-15', value: 105.2 },
          { date: '2024-02-01', value: 108.7 },
          { date: '2024-02-15', value: 112.3 },
          { date: '2024-03-01', value: 115.8 },
          { date: '2024-03-15', value: 118.73 }
        ],
        benchmarkData: [
          { date: '2024-01-01', value: 100 },
          { date: '2024-01-15', value: 102.1 },
          { date: '2024-02-01', value: 103.5 },
          { date: '2024-02-15', value: 105.2 },
          { date: '2024-03-01', value: 106.8 },
          { date: '2024-03-15', value: 108.4 }
        ],
        positionData: [
          { date: '2024-01-01', value: 45 },
          { date: '2024-01-15', value: 52 },
          { date: '2024-02-01', value: 48 },
          { date: '2024-02-15', value: 55 },
          { date: '2024-03-01', value: 50 },
          { date: '2024-03-15', value: 47 }
        ]
      }
    }
  },
  mounted() {
    this.initResizeObserver()
    window.addEventListener('resize', this.handleResize)
    this.$nextTick(() => {
      this.initializeCharts()
    })
  },
  beforeDestroy() {
    this.cleanupResizeObserver()
    window.removeEventListener('resize', this.handleResize)
    this.disposeCharts()
  },
  methods: {
    initResizeObserver() {
      // 使用ResizeObserver监听容器大小变化
      this.resizeObserver = new ResizeObserver(entries => {
        entries.forEach(entry => {
          const { target } = entry
          const chart = this.getChartByContainer(target)
          if (chart) {
            chart.resize()
          }
        })
      })

      // 观察所有图表容器
      ;['profitChart', 'positionPieChart', 'timeBarChart', 'positionLineChart'].forEach(ref => {
        const container = this.$refs[ref]
        if (container) {
          this.resizeObserver.observe(container)
        }
      })
    },
    cleanupResizeObserver() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
        this.resizeObserver = null
      }
    },
    getChartByContainer(container) {
      const refToChart = {
        profitChart: this.charts.profit,
        positionPieChart: this.charts.pie,
        timeBarChart: this.charts.time,
        positionLineChart: this.charts.position
      }
      
      return Object.entries(refToChart).find(([ref]) => this.$refs[ref] === container)?.[1]
    },
    async initializeCharts() {
      this.loading = true
      try {
        await this.$nextTick()
        
        // 初始化所有图表
        const chartConfigs = [
          { ref: 'profitChart', key: 'profit', update: this.updateProfitChart },
          { ref: 'positionPieChart', key: 'pie', update: this.updatePieChart },
          { ref: 'timeBarChart', key: 'time', update: this.updateTimeChart },
          { ref: 'positionLineChart', key: 'position', update: this.updatePositionChart }
        ]

        for (const config of chartConfigs) {
          const container = this.$refs[config.ref]
          if (container) {
            this.charts[config.key] = echarts.init(container, null, {
              renderer: 'canvas',
              width: 'auto',
              height: 'auto'
            })
            config.update()
          }
        }

        // 确保所有图表都正确渲染
        await this.$nextTick()
        this.handleResize()
      } catch (error) {
        console.error('Failed to initialize charts:', error)
      } finally {
        this.loading = false
      }
    },
    updateProfitChart() {
      if (!this.charts.profit) return
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let result = params[0].axisValue + '<br/>'
            params.forEach(param => {
              const value = (param.value - 100).toFixed(2)
              const color = value >= 0 ? '#67C23A' : '#F56C6C'
              const sign = value >= 0 ? '+' : ''
              result += `${param.marker} ${param.seriesName}: <span style="color:${color}">${sign}${value}%</span><br/>`
            })
            return result
          }
        },
        legend: {
          data: ['策略收益', '沪深300'],
          right: 10,
          top: 0
        },
        grid: {
          top: 30,
          right: 10,
          bottom: 20,
          left: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.mockData.profitData.map(item => item.date),
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisTick: { show: false },
          axisLabel: {
            color: '#909399',
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { color: '#F2F6FC' } },
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: {
            color: '#909399',
            fontSize: 12,
            formatter: (value) => {
              const diff = value - 100
              return diff >= 0 ? '+' + diff.toFixed(1) + '%' : diff.toFixed(1) + '%'
            }
          }
        },
        series: [{
          name: '策略收益',
          data: this.mockData.profitData.map(item => item.value),
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 2, color: '#409EFF' },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(64, 158, 255, 0.2)'
            }, {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.05)'
            }])
          }
        }, {
          name: '沪深300',
          data: this.mockData.benchmarkData.map(item => item.value),
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: {
            width: 2,
            color: '#909399',
            type: 'dashed'
          }
        }]
      }
      
      this.charts.profit.setOption(option)
    },
    updatePieChart() {
      if (!this.charts.pie) return
      
      const option = {
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}% ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'center',
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 15,
          formatter: name => {
            const data = this.charts.pie.getOption().series[0].data
            const item = data.find(i => i.name === name)
            return `${name}  ${item.value}%`
          }
        },
        series: [{
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          label: { show: false },
          emphasis: {
            label: { show: false },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.2)'
            }
          },
          data: [
            { value: 35, name: 'BTC' },
            { value: 25, name: 'ETH' },
            { value: 20, name: 'SOL' },
            { value: 15, name: 'BNB' },
            { value: 5, name: 'Others' }
          ],
          itemStyle: {
            borderRadius: 4,
            borderWidth: 2,
            borderColor: '#fff'
          }
        }]
      }
      
      this.charts.pie.setOption(option)
    },
    updateTimeChart() {
      if (!this.charts.time) return
      
      const hours = ['00', '02', '04', '06', '08', '10', '12', '14', '16', '18', '20', '22']
      const data = [5, 8, 12, 9, 11, 13, 15, 12, 10, 8, 9, 11].map(value => ({
        value,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: '#409EFF'
          }, {
            offset: 1,
            color: 'rgba(64, 158, 255, 0.3)'
          }])
        }
      }))

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const hour = params[0].axisValue
            return `${hour}:00 - ${hour}:59<br/>交易量: ${params[0].value}笔`
          },
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          top: 10,
          right: 10,
          bottom: 20,
          left: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hours,
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisTick: { show: false },
          axisLabel: {
            color: '#909399',
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { color: '#F2F6FC' } },
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: {
            color: '#909399',
            fontSize: 12
          }
        },
        series: [{
          data,
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            borderRadius: [4, 4, 0, 0]
          }
        }]
      }
      
      this.charts.time.setOption(option)
    },
    updatePositionChart() {
      if (!this.charts.position) return
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            return `${params[0].axisValue}<br/>持仓比例: ${params[0].value}%`
          }
        },
        grid: {
          top: 10,
          right: 10,
          bottom: 20,
          left: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.mockData.positionData.map(item => item.date),
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisTick: { show: false },
          axisLabel: {
            color: '#909399',
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { color: '#F2F6FC' } },
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: {
            color: '#909399',
            fontSize: 12,
            formatter: '{value}%'
          }
        },
        series: [{
          data: this.mockData.positionData.map(item => item.value),
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 2, color: '#409EFF' },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(64, 158, 255, 0.2)'
            }, {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.05)'
            }])
          }
        }]
      }
      
      this.charts.position.setOption(option)
    },
    handleResize: debounce(function() {
      this.$nextTick(() => {
        Object.values(this.charts).forEach(chart => {
          if (chart) {
            const container = chart.getDom()
            if (container && container.offsetParent !== null) {
              chart.resize({
                width: 'auto',
                height: 'auto'
              })
            }
          }
        })
      })
    }, 300),
    disposeCharts() {
      Object.values(this.charts).forEach(chart => {
        chart && chart.dispose()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.analysis-container {
  padding: 20px;
  background-color: #F2F3F5;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;

  .performance-card {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    width: 100%;
    box-sizing: border-box;

    .metrics-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30px;
      padding-bottom: 24px;
      border-bottom: 1px solid #EBEEF5;

      .metric-item {
        flex: 1;
        text-align: center;
        padding: 0 15px;
        border-right: 1px solid #EBEEF5;

        &:last-child {
          border-right: none;
        }

        .metric-label {
          color: #909399;
          font-size: 14px;
          margin-bottom: 12px;
        }

        .metric-value {
          font-size: 28px;
          font-weight: 500;
          margin-bottom: 8px;
          line-height: 1;

          &.positive {
            color: #67C23A;
          }

          &.negative {
            color: #F56C6C;
          }
        }

        .metric-trend {
          color: #909399;
          font-size: 13px;
        }
      }
    }

    .chart-container {
      margin-bottom: 40px;
      width: 100%;
      
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        width: 100%;

        .select-group {
          display: flex;
          gap: 12px;

          .el-select {
            width: 120px;
          }
        }
      }

      .profit-chart {
        height: 280px;
        width: 100% !important;
      }
    }

    .analysis-section {
      margin-bottom: 40px;

      .section-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 24px;
        padding-left: 12px;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background: #409EFF;
          border-radius: 2px;
        }
      }

      .analysis-grid,
      .trade-analysis-grid {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 24px;
        padding: 24px;
        background: #F8F9FA;
        border-radius: 8px;

        .grid-item {
          .item-label {
            color: #909399;
            font-size: 14px;
            margin-bottom: 8px;
            display: block;
          }

          .item-value {
            font-size: 16px;
            font-weight: 500;
            color: #303133;

            &.positive {
              color: #67C23A;
            }

            &.negative {
              color: #F56C6C;
            }
          }
        }
      }
    }

    .charts-section {
      width: 100%;
      
      .chart-row {
        display: flex;
        gap: 24px;
        margin-bottom: 24px;
        width: 100%;

        .chart-col {
          flex: 1;
          background: #F8F9FA;
          border-radius: 8px;
          padding: 24px;
          width: calc(50% - 12px);
          box-sizing: border-box;

          &.full-width {
            width: 100%;
          }

          .chart-title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 20px;
            font-weight: 500;
          }
        }
      }

      .position-pie-chart,
      .time-bar-chart {
        height: 320px;
        width: 100% !important;
      }

      .position-line-chart {
        height: 240px;
        width: 100% !important;
      }
    }
  }
}
</style> 